package cn.xuewenbao.ucenter.service.impl;

import cn.xuewenbao.ucenter.entity.Vip;
import cn.xuewenbao.ucenter.entity.VipType;
import cn.xuewenbao.ucenter.mapper.VipMapper;
import cn.xuewenbao.ucenter.mapper.VipTypeMapper;
import cn.xuewenbao.ucenter.service.VipService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class VipServiceImpl extends ServiceImpl<VipMapper, Vip> implements VipService {

    @Autowired
    private VipTypeMapper vipTypeMapper;

    @Override
    public Result<Map<String, Object>> getVipInfo(String userId) {
        Result<Map<String, Object>> result = new Result<>();
        QueryWrapper<Vip> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId).orderByDesc("gmt_modified");
        List<Vip> vipList = baseMapper.selectList(wrapper);
        if (vipList == null || vipList.isEmpty()) {
            result.setSuccess(false);
            result.setMessage("用户从未开通过会员");
            return result;
        }
        boolean expire = vipList.get(0).getGmtEnd().before(new Date());
        if (expire) {
            result.setSuccess(true);
            result.setMessage("用户会员已过期");
            Map<String, Object> map = new HashMap<>();
            map.put("expire", true);
            map.put("gmtEnd", vipList.get(0).getGmtEnd());
            result.setResult(map);
            return result;
        }
        result.setSuccess(true);
        result.setMessage("用户已经是会员");
        Map<String, Object> map = new HashMap<>();
        map.put("expire", true);
        map.put("gmtEnd", vipList.get(0).getGmtEnd());
        map.put("leftDay", differentDaysByDate(new Date(), vipList.get(0).getGmtEnd()));
        result.setResult(map);
        return result;
    }

    @Override
    public Result<VipType> getVipTypeInfo(String vipTypeId) {
        VipType vipType = vipTypeMapper.selectById(vipTypeId);
        return Result.OK(vipType);
    }

    @Override
    public Result<List<VipType>> getAllVipType() {
        QueryWrapper<VipType> wrapper = new QueryWrapper<>();
        wrapper.orderByAsc("price");
        List<VipType> vipTypeList = vipTypeMapper.selectList(wrapper);
        return Result.OK(vipTypeList);
    }

    @Override
    public String getOrderDescription(String vipTypeId, String userId) {
        Map<String, Date> map = getVipStartAndEndDate(userId, vipTypeId);
        if (map == null || map.isEmpty() || !map.containsKey("vipStartDate") || !map.containsKey("vipEndDate")) {
            return null;
        }
        Date vipStartDate = map.get("vipStartDate");
        Date vipEndDate = map.get("vipEndDate");
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        return "生效时间： " + df.format(vipStartDate) + "<br>失效时间： " + df.format(vipEndDate);
    }

    @Override
    public String addVip(String memberId, String contentType) {
        Map<String, Date> map = getVipStartAndEndDate(memberId, contentType);
        if (map == null || map.isEmpty() || !map.containsKey("vipStartDate") || !map.containsKey("vipEndDate")) {
            return null;
        }
        Date vipStartDate = map.get("vipStartDate");
        Date vipEndDate = map.get("vipEndDate");
        Vip vip = new Vip();
        vip.setUserId(memberId);
        vip.setGmtStart(vipStartDate);
        vip.setGmtEnd(vipEndDate);
        baseMapper.insert(vip);
        return vip.getId();
    }

    @Override
    public boolean isVip(String userId) {
        QueryWrapper<Vip> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId).orderByDesc("gmt_end");
        List<Vip> vips = baseMapper.selectList(wrapper);
        if (vips == null || vips.size() == 0) {
            return false;
        }
        //截止时间最晚的一条会员记录
        Vip vip = vips.get(0);
        if (new Date().after(vip.getGmtEnd())) {   //当前时间比会员截止时间晚, 会员已过期
            return false;
        }
        return true;
    }

    /*
       根据用户的会员记录和要开通的会员类型, 获得要开通的会员起止时间
     */
    private Map<String, Date> getVipStartAndEndDate(String userId, String vipTypeId) {
        Result<VipType> vipTypeResult = getVipTypeInfo(vipTypeId);
        if (!vipTypeResult.isSuccess()) {
            return null;
        }
        VipType vipType = vipTypeResult.getResult();
        //获取该订单的会员起止时间vipStart, vipEnd
        Date vipStartDate, vipEndDate;
        Result<Map<String, Object>> vipInfoResult = getVipInfo(userId);
        if (!vipInfoResult.isSuccess()) {   //用户从未开通vip
            vipStartDate = new Date();
        } else {    //用户曾经开通过vip
            Map<String, Object> vipInfo = vipInfoResult.getResult();
            boolean expire = (boolean)vipInfo.get("expire");
            if (expire) {   //会员已过期
                vipStartDate = new Date();
            } else {
                Date gmtEnd = (Date)vipInfo.get("gmtEnd");
                vipStartDate = new Date(gmtEnd.getTime() + 1);
            }
        }
        vipEndDate = new Date(vipStartDate.getTime() + (long) vipType.getDay() * 24 * 3600 * 100);

        Map<String, Date> map = new HashMap<>();
        map.put("vipStartDate", vipStartDate);
        map.put("vipEndDate", vipEndDate);
        return map;
    }

    /*
       计算两个日期相差的天数，不足24小时的算一天
     */
    private int differentDaysByDate(Date date1,Date date2) {
        long millisecond;
        if (date1.before(date2)) {
            millisecond = date2.getTime() - date1.getTime();
        } else {
            millisecond = date1.getTime() - date2.getTime();
        }
        int days = (int) (millisecond / (1000*3600*24));
        if ((millisecond % (1000 * 3600 * 24)) > 0) {
            days += 1;
        }
        return days;
    }
}
